<?php


namespace addons\unishop\controller;
use addons\unishop\extend\Hashids;
use addons\unishop\model\Area;
use addons\unishop\model\Config;
use addons\unishop\model\Evaluate;
use addons\unishop\model\Product;
use app\admin\model\unishop\Coupon as CouponModel;
use addons\unishop\model\DeliveryRule as DeliveryRuleModel;
use addons\unishop\model\OrderRefund;
use app\admin\model\unishop\OrderRefundProduct;
use think\Db;
use think\Exception;
use addons\unishop\model\Address as AddressModel;
use think\Hook;
use think\Loader;

/**
 * 订单
 */
class Downs extends Base
{

    /**
     * 允许频繁访问的接口
     * @var array
     */
    protected $frequently = [''];

    protected $noNeedLogin = [''];


    /**
     * 我的下级
     */
    public function getmydown()
    {

        $userinfo = $this->auth->getUser();

        // 优化后的代码
        $parentId = $userinfo['id'];
// 一次性获取所有相关的用户数据
        $users = Db::name('user')->where('agentid', $parentId)->select();

        if (!empty($users)) {
            // 提取所有子用户的ID
            $userIds = array_column($users, 'id');

            // 一次性获取所有二级用户数据
            $children = Db::name('user')->where('agentid', 'in', $userIds)->select();

            // 按照agentid分组子用户数据
            $childrenGrouped = [];
            foreach ($children as $child) {
                $child['createtime'] = date('Y-m-d H:i:s', $child['createtime']);
                $childrenGrouped[$child['agentid']][] = $child;
            }

            // 处理一级用户数据并关联子用户
            foreach ($users as $key => $user) {
                $users[$key]['expanded'] = false;
                $users[$key]['createtime'] = date('Y-m-d H:i:s', $user['createtime']);
                $users[$key]['children'] = isset($childrenGrouped[$user['id']]) ? $childrenGrouped[$user['id']] : [];
            }

            $user = $users;
        } else {
            $user = [];
        }


        $this->success('', $user);




    }




    /**
     * 获取小程序太阳吗
     */
    public function getqrcode(){

        $uid=$this->auth->id;

        $key1=Db::name('unishop_config')->where(['id'=>17])->find();
        $key2=Db::name('unishop_config')->where(['id'=>18])->find();

        $appid=$key1['value'];
        $appsecret=$key2['value'];


        $access_token = $this->getaccess_token($appid, $appsecret);

        $access_token = $access_token['access_token'];

        $request_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $request_data = array(
            'scene' =>$uid,
            'page' => 'pages/index/index',
            'width' => '690',
            'is_hyaline'=>true
        );

        $img =$this->https_request($request_url, $request_data, 'json');



        $imgfile="/uploads/qrcode/".md5($uid).".png";

        $filename =  ".".$imgfile;//要生成的图片名字


        $file = fopen($filename, "w");//打开文件准备写入

        fwrite($file, $img);//写入

        fclose($file);//关闭

        $this->success('',cdnurl($imgfile,true));

    }




    public function getaccess_token($appid, $appsecret)  {

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, 0);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);


        // close curl resource to free up system resources
    }

    public function https_request($url = '', $param = [], $contentType = ''){
        $ch = curl_init();

        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);

        // 请求参数类型
        $param = $contentType == 'json' ? json_encode($param) : $param;

        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // post提交
        if ($param) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }

        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行并接收响应结果
        $output = curl_exec($ch);

        // 关闭curl
        curl_close($ch);

        return $output !== false ? $output : false;
    }


    /**
     * 提交代理申请
     * adda:this.adda,
     * addb:this.addb,
     * addc:this.addc,
     * phone:this.phone,
     * name:this.name,
     * address:this.address,
     */
    public function handleSubmit(){

        $uid=$this->auth->id;

        $data=$this->request->param();

        foreach ($data as $key=>$value){
            if (!$value){
                $this->error('请填写完整信息');
            }
        }


        $daili=Db::name('user_daili')->where(['user_id'=>$uid])->find();

        if ($daili){
            $this->error('您已提交过申请');
        }

        Db::name('user_daili')->insert([
            'user_id'=>$uid,
            'add_a'=>$data['adda'],
            'add_b'=>$data['addb'],
            'add_c'=>$data['addc'],
            'phone'=>$data['phone'],
            'name'=>$data['name'],
            'address'=>$data['address'],
            'createtime'=>time()
        ]);

        $this->success('提交成功,请耐心等待审核');


    }

    /**
     * 我的代理信息
     */
    public function getmydaili(){

        $uid=$this->auth->id;

        $daili=Db::name('user_daili')->where(['user_id'=>$uid])->find();

        if ($daili){
            $daili['createtime']=date('m-d H:i',$daili['createtime']);
        }

        $this->success('',$daili);

    }

}
